<script setup>
import { ref,onMounted } from 'vue'
import axios from "axios"
import {ElMessage,ElMessageBox,ElLoading} from "element-plus"

let list=ref([])
let query=ref({
  "page":1,
  "size":2,
  "name":""
})

let total=ref(0)

const getData=()=>{
  axios.get("http://127.0.0.1:8000/shopping/shopping/",{params:query.value}).then((res)=>{
    //将接口返回的数据展示存储到变量中
    list.value=res.data.results
    //将总的记录数赋值
    total.value=res.data.count
  })
}
onMounted(()=>{
  //列表
  getData()

})
let staff=ref({
  "name": "",
  "price": "",
})

//定义一个变量 控制对话框的显示和隐藏
let show=ref(false);
//定义一个id 将要修改的id数据接出来
let id=null

//编辑
const edit=(info)=>{
  show.value=true
  id=info.id
    //点编辑的时候 让show变为true 对话框展示
  axios.get(`http://127.0.0.1:8000/shopping/shopping/${info.id}/`).then(res=>{
    console.log(res)
    staff.value.name=res.data.name
    staff.value.price=res.data.price
  })
}


//save方法 执行编辑的接口
const save=()=>{
 //console.log(goods.value)
    axios.put(`http://127.0.0.1:8000/shopping/shopping/${id}/`,staff.value).then((res)=>{
    if(res.data){
        //更新
        getData()
        //提示
        ElMessage({
            message:"修改成功",
            type:"success",
        });
        //清空
        staff.value={
          "name": "",
          "price": "",
          "num": ""
       
        }
        //挂框
        show.value=false
 }
 //成功后  更新  提示   清空绑定的对象  关框
 })
}

//取消
const cancel=()=>{
    show.value=false
    staff.value={
      "name": "",
      "price": "",
           
    }
}

const changepage=(num)=>{
    query.value.page=num
    getData()
}
</script>


<template>
    <el-table :data="list" border style="width: 100%">
      <el-table-column prop="name" label="商品名称"  />
      <el-table-column prop="price" label="商品价格"  />

  
      <el-table-column  label="操作" >
        <template #default="scope">
          <el-button type="danger" @click="handleDelete(scope.row.id)">添加</el-button>
          <el-button type="success" @click="edit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
      </el-table>
      <!-- 分页导航 -->
      <el-pagination background layout="prev, pager, next" :total="total" :page-size="query.size" @current-change="changepage"/>
  
      <el-dialog
        v-model="show"
        title="Tips"
        width="500"
      >  <div>
          <p>商品名称:<el-input v-model="staff.name" style="width: 240px" placeholder="Please input name" /></p >
          <p>商品价格:<el-input v-model="staff.price" style="width: 240px" placeholder="Please input price" /></p >
          
  
          
      </div>
  
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save "> 确认 </el-button>
      
        </div>
      </template>
    </el-dialog>
      
      
  
  
  </template>
  
  <style scoped>
  
  </style>
  
